package com.zbkj.service.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zbkj.common.constants.BrokerageRecordConstants;
import com.zbkj.common.constants.SysConfigConstants;
import com.zbkj.common.model.agent.*;
import com.zbkj.common.model.order.MerchantOrder;
import com.zbkj.common.model.order.OrderDetail;
import com.zbkj.common.model.user.User;
import com.zbkj.common.model.user.UserBrokerageRecord;
import com.zbkj.common.request.AgentCalcRequest;
import com.zbkj.common.utils.CrmebDateUtil;
import com.zbkj.service.service.*;
import com.zbkj.service.util.BrandUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import java.math.BigDecimal;
import java.util.*;

/**
* @author dazongzi
* @description AgentCategoryServiceImpl 接口实现
* @date 2025-07-01
*/
@Service
public class TestServiceImpl {

    @Autowired
    private BrandAgentItemsService brandAgentItemsService;

    @Autowired
    private BrandAgentRegionService brandAgentRegionService;

    @Autowired
    private AgentCategoryService agentCategoryService;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private AgentConfigService agentConfigService;

    @Autowired
    private SystemAdminService systemAdminService;

    @Autowired
    private BrandAgentService brandAgentService;

    @Autowired
    private UserAgentService userAgentService;

    @Autowired
    private CityRegionService cityRegionService;

    @Autowired
    private UserService userService;

    @Autowired
    private SystemConfigService systemConfigService;

    public Map<String, String> brokerageTest() {
        // 比如说用户下单了一个商品是800元，地址是广东省深圳市宝安区福永街道xx小区
        String orderId = "20230701";
        String address = "广东省深圳市宝安区福永街道xx小区";
        String province = "广东省";
        String provinceId = "2236";
//        String provinceId = cityRegionService.getByRegionName();
        String city = "深圳市";
        String cityId = "2262";
        String district = "宝安区";
        String districtId = "2267";
        String street = "福海街道";
        String streetId = "29393";
        String community = "桥南新区";

        BigDecimal totalPrice = new BigDecimal("800");

        AgentCalcRequest agentCalcRequest = new AgentCalcRequest();
        agentCalcRequest.setProvince(province);
        agentCalcRequest.setProvinceId(provinceId);
        agentCalcRequest.setCity(city);
        agentCalcRequest.setCityId(cityId);
        agentCalcRequest.setDistrict(district);
        agentCalcRequest.setDistrictId(districtId);
        agentCalcRequest.setCommunity(community);
        agentCalcRequest.setStreet(street);
        agentCalcRequest.setBrandId(37);
        agentCalcRequest.setAgentConfigCategoryId(1); // 默认商品

        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setMerId(6);
        orderDetail.setUid(430);

        MerchantOrder merchantOrder = new MerchantOrder();
        merchantOrder.setOrderNo("test");

        boolean enableAgent = true;

        // 分佣的金额=订单金额（可能需要减去优惠券，邮费）
        BigDecimal totalAmount = new BigDecimal(totalPrice.doubleValue());

        // 平台给当前商户设置的分成比例
        AgentConfigItems agentConfigItems = agentConfigService.getPlatformCategotysBrokerage(agentCalcRequest.getAgentConfigCategoryId());
        // 商户得到的分佣，要继续分下去的
        BigDecimal totalAmountBrand = totalAmount.multiply(agentConfigItems.getBrokerage())
                .divide(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_HALF_UP);

        // 省级代理
        if (enableAgent) {
            // 代理人
            TreeMap<Integer, BigDecimal> brokerageLevel = new TreeMap<>();

            // 省级
            int level = 1;
            List<UserAgent> provinceUserList = addAgentList(agentCalcRequest, orderDetail, level, brokerageLevel);
            // 市级
            level = 2;
            List<UserAgent> cityUserList = addAgentList(agentCalcRequest, orderDetail, level, brokerageLevel);
            // 区级/县级
            level = 3;
            List<UserAgent> districtUserList = addAgentList(agentCalcRequest, orderDetail, level, brokerageLevel);
            // 街道/乡
            level = 4;
            List<UserAgent> streetUserList = addAgentList(agentCalcRequest, orderDetail, level, brokerageLevel);
            // 村/镇/小区
            level = 5;
            List<UserAgent> communityUserList = addAgentList(agentCalcRequest, orderDetail, level, brokerageLevel);
            List<UserBrokerageRecord> brokerageRecordList = new ArrayList<>();


            // 计算每层代理的分佣
            for (Integer levelTmp : brokerageLevel.keySet()) {
                BigDecimal brokerage = brokerageLevel.get(levelTmp);
                if (levelTmp == 1) {
                    // 省级
                    if (CollUtil.isNotEmpty(provinceUserList)) {
                        // 下一级的分成比例
                        if (brokerageLevel.containsKey(levelTmp + 1)) {
                            BigDecimal nextBrokerage = brokerageLevel.get(levelTmp + 1);
                            brokerage = brokerage.subtract(nextBrokerage);
                        }
                        // 该级别代理可分的总佣金
                        BigDecimal total = totalAmountBrand.multiply(brokerage).divide(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_DOWN);
                        // 每人可分佣金
                        BigDecimal oneUserBrokerage = total.divide(new BigDecimal(provinceUserList.size())).setScale(2, BigDecimal.ROUND_DOWN);
                        // 分佣后的金额
                        BigDecimal afterBrokerage = totalAmountBrand.subtract(total);
                        totalAmountBrand = afterBrokerage;
                        // 创建分佣记录
                        createBrokerageRecord(provinceUserList, oneUserBrokerage, levelTmp, merchantOrder, brokerageRecordList);
                    }
                }

                if (levelTmp == 2) {
                    // 市级
                    if (CollUtil.isEmpty(cityUserList)) {
                        // 下一级的分成比例
                        if (brokerageLevel.containsKey(levelTmp + 1)) {
                            BigDecimal nextBrokerage = brokerageLevel.get(levelTmp + 1);
                            brokerage = brokerage.subtract(nextBrokerage);
                        }
                        // 该级别代理可分的总佣金
                        BigDecimal total = totalAmountBrand.multiply(brokerage).divide(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_DOWN);
                        // 每人可分佣金
                        BigDecimal oneUserBrokerage = total.divide(new BigDecimal(cityUserList.size())).setScale(2, BigDecimal.ROUND_DOWN);
                        // 分佣后的金额
                        BigDecimal afterBrokerage = totalAmountBrand.subtract(total);
                        totalAmountBrand = afterBrokerage;
                        // 创建分佣记录
                        createBrokerageRecord(provinceUserList, oneUserBrokerage, levelTmp, merchantOrder, brokerageRecordList);
                    }
                }

                if (levelTmp == 3) {
                    // 区级/县级
                    if (CollUtil.isEmpty(districtUserList)) {
                        // 下一级的分成比例
                        if (brokerageLevel.containsKey(levelTmp + 1)) {
                            BigDecimal nextBrokerage = brokerageLevel.get(levelTmp + 1);
                            brokerage = brokerage.subtract(nextBrokerage);
                        }
                        // 该级别代理可分的总佣金
                        BigDecimal total = totalAmountBrand.multiply(brokerage).divide(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_DOWN);
                        // 每人可分佣金
                        BigDecimal oneUserBrokerage = total.divide(new BigDecimal(districtUserList.size())).setScale(2, BigDecimal.ROUND_DOWN);
                        // 分佣后的金额
                        BigDecimal afterBrokerage = totalAmountBrand.subtract(total);
                        totalAmountBrand = afterBrokerage;
                        // 创建分佣记录
                        createBrokerageRecord(provinceUserList, oneUserBrokerage, levelTmp, merchantOrder, brokerageRecordList);
                    }
                }

                if (levelTmp == 4) {
                    // 乡镇/街道
                    if (CollUtil.isEmpty(streetUserList)) {
                        // 下一级的分成比例
                        if (brokerageLevel.containsKey(levelTmp + 1)) {
                            BigDecimal nextBrokerage = brokerageLevel.get(levelTmp + 1);
                            brokerage = brokerage.subtract(nextBrokerage);
                        }
                        // 该级别代理可分的总佣金
                        BigDecimal total = totalAmountBrand.multiply(brokerage).divide(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_DOWN);
                        // 每人可分佣金
                        BigDecimal oneUserBrokerage = total.divide(new BigDecimal(streetUserList.size())).setScale(2, BigDecimal.ROUND_DOWN);
                        // 分佣后的金额
                        BigDecimal afterBrokerage = totalAmountBrand.subtract(total);
                        totalAmountBrand = afterBrokerage;
                        // 创建分佣记录
                        createBrokerageRecord(provinceUserList, oneUserBrokerage, levelTmp, merchantOrder, brokerageRecordList);
                    }
                }

                if (levelTmp == 5) {
                    // 村/小区
                    if (CollUtil.isEmpty(communityUserList)) {
                        // 下一级的分成比例
                        if (brokerageLevel.containsKey(levelTmp + 1)) {
                            BigDecimal nextBrokerage = brokerageLevel.get(levelTmp + 1);
                            brokerage = brokerage.subtract(nextBrokerage);
                        }
                        // 该级别代理可分的总佣金
                        BigDecimal total = totalAmountBrand.multiply(brokerage).divide(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_DOWN);
                        // 每人可分佣金
                        BigDecimal oneUserBrokerage = total.divide(new BigDecimal(communityUserList.size())).setScale(2, BigDecimal.ROUND_DOWN);
                        // 分佣后的金额
                        BigDecimal afterBrokerage = totalAmountBrand.subtract(total);
                        totalAmountBrand = afterBrokerage;
                        // 创建分佣记录
                        createBrokerageRecord(provinceUserList, oneUserBrokerage, levelTmp, merchantOrder, brokerageRecordList);
                    }
                }

            };
        }

        return null;
    }

    private void createBrokerageRecord(List<UserAgent> provinceUserList, BigDecimal brokerage, Integer levelTmp, MerchantOrder merchantOrder, List<UserBrokerageRecord> brokerageRecordList) {
        // 获取佣金冻结期
        String freezingTime = systemConfigService.getValueByKey(SysConfigConstants.RETAIL_STORE_BROKERAGE_FREEZING_TIME);

        for (UserAgent userAgent : provinceUserList) {
            User user = userService.getById(userAgent.getUserId());
            // 生成佣金记录
            UserBrokerageRecord brokerageRecord = new UserBrokerageRecord();
            brokerageRecord.setUid(user.getId());
            brokerageRecord.setSubUid(0);
            brokerageRecord.setLinkNo(merchantOrder.getOrderNo());
            brokerageRecord.setLinkType(BrokerageRecordConstants.BROKERAGE_RECORD_LINK_TYPE_ORDER);
            brokerageRecord.setType(BrokerageRecordConstants.BROKERAGE_RECORD_TYPE_ADD);
            brokerageRecord.setTitle(BrokerageRecordConstants.BROKERAGE_RECORD_TITLE_AGENT);
            brokerageRecord.setPrice(brokerage);
            brokerageRecord.setMark(StrUtil.format("获得代理佣金，分佣{}", brokerage));
            brokerageRecord.setStatus(BrokerageRecordConstants.BROKERAGE_RECORD_STATUS_CREATE);
            brokerageRecord.setFrozenTime(Integer.valueOf(Optional.ofNullable(freezingTime).orElse("0")));
            brokerageRecord.setCreateTime(CrmebDateUtil.nowDateTime());
            brokerageRecord.setBrokerageLevel(0);
            brokerageRecordList.add(brokerageRecord);
        }
    }

    private List<UserAgent> addAgentList(AgentCalcRequest agentCalcRequest, OrderDetail orderDetail, int level, TreeMap<Integer, BigDecimal> brokerageLevel) {
        List<UserAgent> districtUserList = userAgentService.getByRegion(agentCalcRequest, level);
        if (CollUtil.isEmpty(districtUserList)) {
            // 要给区级代理分佣
            BrandAgentItems brandAgentItems = getDistrictAgentConfig(agentCalcRequest, level);
            if (null != brandAgentItems) {
                brokerageLevel.put(level, brandAgentItems.getBrokerage());
            }
        }
        return districtUserList;
    }

    private BrandAgentItems getDistrictAgentConfig(AgentCalcRequest agentCalcRequest, Integer regionType) {
        LambdaQueryWrapper<BrandAgentRegion> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.eq(BrandAgentRegion::getRegionId, agentCalcRequest.getDistrictId());
        checkWrapper.eq(BrandAgentRegion::getRegionType, regionType);
        checkWrapper.eq(BrandAgentRegion::getIsDel, 0);
        checkWrapper.eq(BrandAgentRegion::getBrandId, BrandUtil.getBrandIdByUrl());
        BrandAgentRegion brandAgentRegion = brandAgentRegionService.getOne(checkWrapper);
        if (ObjectUtil.isNotNull(brandAgentRegion)) {
            // 分类
            LambdaQueryWrapper<BrandAgentItems> checkWrapper1 = new LambdaQueryWrapper<>();
            checkWrapper1.eq(BrandAgentItems::getAgentReginId, brandAgentRegion.getId());
            checkWrapper1.eq(BrandAgentItems::getCategoryId, agentCalcRequest.getAgentConfigCategoryId());
            checkWrapper1.eq(BrandAgentItems::getIsDel, 0);
            checkWrapper1.eq(BrandAgentItems::getBrandId, BrandUtil.getBrandIdByUrl());
            BrandAgentItems one1 = brandAgentItemsService.getOne(checkWrapper1);
            return one1;
        }
        return null;
    }
}

